package com.menghao.sso.server.registry;

import com.menghao.sso.server.model.ticket.Ticket;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>默认的票据注册实现.<br>
 *
 * @author menghao.
 * @version 2017/11/21.
 */
public final class DefaultTicketRegistry implements TicketRegistry {

    private final Log log = LogFactory.getLog(getClass());

    private final Map<String, Ticket> cache = new HashMap<String, Ticket>();

    public synchronized void addTicket(final Ticket ticket) {
        if (ticket == null) {
            throw new IllegalArgumentException("ticket cannot be null");
        }
        log.debug("Added ticket [" + ticket.getId() + "] to registry.");
        this.cache.put(ticket.getId(), ticket);
    }

    public synchronized Ticket getTicket(final String ticketId) {
        log.debug("Attempting to retrieve ticket [" + ticketId + "]");
        final Ticket ticket = this.cache.get(ticketId);
        if (ticket != null) {
            log.debug("Ticket [" + ticketId + "] found in registry.");
        }
        return ticket;
    }

    public synchronized boolean deleteTicket(final String ticketId) {
        log.debug("Removing ticket [" + ticketId + "] from registry");
        return (this.cache.remove(ticketId) != null);
    }

    public synchronized Collection getTickets() {
        return Collections.unmodifiableCollection(this.cache.values());
    }
}
